package 代码随想2._4字符串;

/**
 * @author XXX
 * @date 2024-01-16 21:27
 */

/**
 * https://leetcode.cn/problems/reverse-string-ii/description/
 */
public class _2反转字符串II {
    public String reverseStr(String s, int k) {
        char[] ch = s.toCharArray();
        // 1. 每隔 2k 个字符的前 k 个字符进行反转
        for(int i=0; i<ch.length; i += 2*k){
            // 2. 剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符
            if(i+k <= ch.length){
                reverse(ch, i, i+k-1);
                continue;
            }
            // 3. 剩余字符少于 k 个，则将剩余字符全部反转
            reverse(ch, i, ch.length -1);
        }
        return new String(ch);
    }

    void reverse(char[] ch, int i, int j){
        for(;i<j;i++,j--){
            char tmp = ch[i];
            ch[i] = ch[j];
            ch[j] = tmp;
        }
    }


    public String reverseStr2(String s, int k) {
        char[] ch = s.toCharArray();
        for(int i=0; i<ch.length; i+=2*k){
            int start = i;
            // 判断尾数够不够k个来取决end指针的位置
            int end = Math.min(ch.length - 1,start + k - 1);
            while(start<end){
                char tmp = ch[start];
                ch[start] = ch[end];
                ch[end] = tmp;

                start++;
                end--;
            }
        }
        return new String(ch);
    }
}
